﻿#pragma once
#include "Comm.h"
#include "Thread.h"
#include "ThreadLock.h"

namespace COMM
{
	class COMM_API ThreadPool
	{
	public:
		enum{ DefaultThreadsCount = 4 };
		typedef int (*ThreadPoolProc)(int index, CommType& arg);
		// return: *** do not release the instance before thread is run over.
		static ThreadPool* Start(ThreadPoolProc proc, const CommType& arg = CommType::Null,
			int threadCount = DefaultThreadsCount, const char* poolName = NULL, bool suspend = false, unsigned int timeoutMs = -1);

		ThreadPool(int threadCount = DefaultThreadsCount, const char* poolName = NULL, unsigned int timeoutMs = -1);
		virtual ~ThreadPool(void);
		Thread* operator[](int index);
		const char* Name() const;
		void Start();
		void Stop(bool cancelThread=false);

	protected:
		virtual int Process(int index) = 0;
	private:
		class WorkerThread : public Thread
		{
		public:
			WorkerThread(ThreadPool* pool, int index, const char* name);
		private:
			virtual int Process();
			ThreadPool* m_pool;
			int m_index;
		};
		ThreadLock m_threadLock;
		Thread** m_threadList;
		unsigned int m_timeoutMs;
		int m_threadCount;
		String m_name;
		bool m_started;
	};
}


